﻿using Huasky.MyWrod.Common.Util;
using Serilog;
using Serilog.Events;
using Serilog.Extensions.Logging;

namespace Huasky.MyWrod.Web.Core.Extensions;

public static class LoggerConfig
{
    public static void Init()
    {
        var cfg = new LoggerConfiguration()
                 .OverrideAspNetLogLevel()
                 .WriteToFile()
                 .WriteTo.Console();

        Log.Logger = cfg.CreateLogger();
        var logFactory = new SerilogLoggerFactory();
        LoggerHelper.Init(logFactory);
    }

    static LoggerConfiguration OverrideAspNetLogLevel(this LoggerConfiguration loggerCfg)
    {
        var loggers = new[]
        {
            "Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor",
            "Microsoft.AspNetCore.Authorization.DefaultAuthorizationService",
            "Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager",
            "Microsoft.AspNetCore.Hosting.Diagnostics",
            "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker",
            "Microsoft.AspNetCore.Routing.EndpointMiddleware",
        };

        foreach (var logger in loggers)
        {
            loggerCfg.MinimumLevel.Override(logger, LogEventLevel.Warning);
        }

        return loggerCfg;
    }


    static LoggerConfiguration WriteToFile(this LoggerConfiguration loggerCfg)
    {
        var logPath = Path.GetFullPath("../logs");
        var fileMaxSize = 100 * 1024 * 1024;

        loggerCfg.WriteTo.File(Path.Combine(logPath, "log-.txt"),
                      rollingInterval: RollingInterval.Day,
                      rollOnFileSizeLimit: true,
                      fileSizeLimitBytes: fileMaxSize)
                 .WriteTo.File(Path.Combine(logPath, "err-.txt"), LogEventLevel.Error,
                      rollingInterval: RollingInterval.Day,
                      rollOnFileSizeLimit: true,
                      fileSizeLimitBytes: fileMaxSize);

        return loggerCfg;
    }

}
